package secondPart;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther : yxpweb
 * @Date : 2021/8/10 11:27
 * @Description: atomicInteger 解决多线程的竞争
 * https://blog.csdn.net/mryang125/article/details/81879096
 */
public class ThreadDemo15 {

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

//    private static ReentrantLock reentrantLock = new ReentrantLock(); // 这种方式肯定能解决

    private static Runnable gameTask = () -> {
        try {
//            reentrantLock.lock();
            System.out.println(atomicInteger.get() + "Thread start begin ");
            Thread.sleep(2000);
            System.out.println(atomicInteger.incrementAndGet() + "Thread start end ");
//            throw new NullPointerException(); // 莫奈线程执行报错
//            reentrantLock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        for (int i = 0; i < 5; i++) {
            System.out.println(i + "main");
            Future future = null;
            try {
                future = executorService.submit(gameTask);
                Object o = future.get(3, TimeUnit.SECONDS);
                System.out.println(o);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
                future.cancel(true);
            }

//            executorService.execute(gameTask);
        }
        executorService.shutdown();
    }
}
